package com.wpp.mongodb;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author wpp25
 * @date 2021/6/19 21:11
 * @description：
 */
public class ClientTest {


    MongoClient mongoClient;
    MongoCollection<Document> collection;
    @Before
    public void before(){
        mongoClient = new MongoClient(Constants.IP, Constants.port);
        MongoDatabase database = mongoClient.getDatabase(Constants.DATABASE);
        collection = database.getCollection(Constants.COLLECTION);
    }

    @Test
    public void insertTest(){

        Document document = Document.parse(
                "{name:'fuli',city:'bj',birth_day:new ISODate('2001-08-01'),expectSalary:28000}");
        collection.insertOne(document );
    }
    @Test
    public void queryTest(){
        Document sdoc=new Document();
        //按expectSalary倒序
        sdoc.append("expectSalary", -1);
        FindIterable<Document> findIterable = collection.find().sort(sdoc);
        for (Document document : findIterable) {
            System.out.println(document);
        }
    }
    @Test
    public void queryFilterTest(){
        Document sdoc=new Document();
//按expectSalary倒序
        sdoc.append("expectSalary", -1);
        FindIterable<Document> findIterable =
                collection.find(Filters.gt("expectSalary",21000)).sort(sdoc);
        for (Document document : findIterable) {
            System.out.println(document);
        }

    }

    @After
    public void closeTest(){
        mongoClient.close();
    }


}
